package com.atguigu.practice;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    private DatagramSocket socket=null;
    //参数的端口
    public UdpEchoServer(int port) throws SocketException {
        socket=new DatagramSocket(port);
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer   server=new UdpEchoServer(9090);
        server.start();
    }

    //启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //循环里处理一次请求
            //1.读取请求并解析
            //调用recevie时需要构造一个空的DatagramPacket对象，然后把对象交给recevie,在recevie里负责把读到的对象进行填充
            DatagramPacket packet=new DatagramPacket(new byte[1024],1024);
            socket.receive(packet);
            //把Packet对象转成字符串，方便打印
            String request=new String(packet.getData(),0,packet.getLength());
            //2.根据请求计算响应
            String response=process(request);
            //3.把响应写到客户端
            DatagramPacket responsePacket=new DatagramPacket(response.getBytes(),response.getBytes().length,
                    packet.getSocketAddress());
            socket.send(responsePacket);
            //4.打印一个日志，记录当前情况
            System.out.printf("[%s:%d] req: %s; resp: %s\n",packet.getAddress().toString(),
                    packet.getPort(),request,response);
        }
    }

    //当前写的是一个回显服务器，响应和请求是一样的
    public String process(String request) {
        return request;
    }
}
